package com.wyp168.juc.sync;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName ThreadDemo002
 * @Description TODO
 * @Author wyp168
 * @Date 2022/9/4 11:47
 */

class Share02 {
    private int num = 0;

    Lock lock = new ReentrantLock();
    Condition condition= lock.newCondition();

    // +1 方法
    public void incr() {
        try {
            //上锁
            lock.lock();
            //判断
            if( num != 0) {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //执行
            num ++;
            System.out.println(Thread.currentThread().getName() + "--->" + num);
            //通知
            condition.signalAll();
        } finally {
            //解锁
            lock.unlock();
        }
    }

    // -1方法
    public void sub() {
        try {
            //上锁
            lock.lock();
            //判断
            if ( num != 1) {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //执行
            num --;
            System.out.println(Thread.currentThread().getName() + "--->" + num);
            //通知
            condition.signalAll();
        } finally {
            //解锁
            lock.unlock();
        }
    }
}
public class ThreadDemo002 {
    public static void main(String[] args) {
        Share02 share = new Share02();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                share.incr();
            }
        }, "AA").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                share.sub();
            }
        }, "BB").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                share.incr();
            }
        }, "CC").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                share.sub();
            }
        }, "DD").start();
    }
}
